; Waits for a keypress, then
; returns it in A
WaitKey:
	;push af
WaitKeyLoop:
	call GetKey
	or a
	jr z, WaitKeyLoop
	;pop af
	ret

; Waits for all keys to be unpressed
FlushKeys:
	push af
FlushKeyLoop:
	call GetKey
	or a
	jr nz, FlushKeyLoop
	pop af
	ret

GetKey:
	push bc
	push de
	push hl
gs_GetK2:
	ld b,7
gs_GetK_loop:

	ld a,7
	sub b
	ld hl,gs_keygroups
	ld d,0
	ld e,a
	add hl,de
	ld a,(hl)
	ld c,a

	ld a,0ffh           ;resets the keypad.
	out (1),a           ;'Required syntax' :)
	ld a,c
	out (1),a
	in a,(1)            ;'Required Syntax'

	ld de,0
	cp 254
	jr z,gs_GetK_254
	cp 253
	jr z,gs_GetK_253
	cp 251
	jr z,gs_GetK_251
	cp 247
	jr z,gs_GetK_247
	cp 239
	jr z,gs_GetK_239
	cp 223
	jr z,gs_GetK_223
	cp 191
	jr z,gs_GetK_191
	cp 127
	jr z,gs_GetK_127

gs_GetK_loopend:

	djnz gs_GetK_loop

	xor a
	ld (gs_keymem),a
	jr gs_GetK_end

gs_GetK_127:
	inc e
gs_GetK_191:
	inc e
gs_GetK_223:
	inc e
gs_GetK_239:
	inc e
gs_GetK_247:
	inc e
gs_GetK_251:
	inc e
gs_GetK_253:
	inc e
gs_GetK_254:

	push de
	ld a,7
	sub b
	add a,a
	add a,a
	add a,a
	ld d,0
	ld e,a
	ld hl,gs_keygroup1
	add hl,de
	pop de
	add hl,de
	ld a,(hl)

	;push hl
	;push de
	;push af
	;bcall(_puts)
	;ld	hl,2567
	;ld	(currow),hl
	;ld	h,0
	;ld	l,a
	;bcall(_disphl)
	;pop af
	;pop de
	;pop hl

	ld d,a
	ld a,(gs_keymem)
	cp d
	jr z,gs_GetK_end
	ld a,d
	ld (gs_keymem),a


gs_GetK_end:
	pop hl
	pop de
	pop bc
	ret

gs_keygroups:
	db 0feh, 0fdh, 0fbh, 0f7h, 0efh, 0dfh, 0bfh
gs_keygroup1:
	db 01h, 02h, 03h, 04h, 00h, 00h, 00h, 00h
gs_keygroup2:
	db 09h, 0Ah, 0Bh, 0Ch, 0Dh, 0Eh, 0Fh, 00h
gs_keygroup3:
	db 11h, 12h, 13h, 14h, 15h, 16h, 17h, 00h
gs_keygroup4:
	db 19h, 1Ah, 1Bh, 1Ch, 1Dh, 1Eh, 1Fh, 20h
gs_keygroup5:
	db 21h, 22h, 23h, 24h, 25h, 26h, 27h, 28h
gs_keygroup6:
	db 00h, 2Ah, 2Bh, 2Ch, 2Dh, 2Eh, 2Fh, 30h
gs_keygroup7:
	db 31h, 32h, 33h, 34h, 35h, 36h, 37h, 38h 
